package com.dishdex.menuhub.console.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CannedAccessControlList;
import com.dishdex.menuhub.module.utils.Response;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;

/**
 * ClassName:
 * Package: com.dishdex.menuhub.console.controller
 * Description:
 *
 * @Author:
 * @Create 2025/9/23 14:19
 * @Version 1.0
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.ClientBuilderConfiguration;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@RestController
public class PhotoController {

    @RequestMapping("/save")
    public Response save(@RequestParam("file") MultipartFile file) throws Exception {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String region = "cn-hangzhou";
        String bucketName = "dishbucket";

        String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");

        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        ClientBuilderConfiguration clientConfig = new ClientBuilderConfiguration();
        clientConfig.setSignatureVersion(SignVersion.V4);

        /*
         * 构建OSSClient对象
         * */
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialProvider)
                .clientConfiguration(clientConfig)
                .region(region)
                .build();

        /*
         * 创建存储空间(Bucket)并设置权限
         * */
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        /*
         *生成文件名中的日期
         * */
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMM/dd");
        String datePath = now.format(dtf);

        //生成唯一字符串
        String uniqueString = UUID.randomUUID().toString();

        /*
         * 生成文件类型
         * */
        String originalFileName = file.getOriginalFilename();
        int lastDotIndex = originalFileName.lastIndexOf(".");
        String fileType = originalFileName.substring(lastDotIndex + 1).toLowerCase();

        String fileName;
        if (fileType.equals("jpg") || fileType.equals("png")) {
            /*
             * 生成图片的宽度和高度
             * */
            InputStream inputStream = file.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);
            int width = image.getWidth();
            int height = image.getHeight();

            //图片的文件名
            fileName = "image/" + datePath + "/" + uniqueString + "_" + width + "x" + height + "." + fileType;
        } else {
            fileName = "file/" + datePath + "/" + uniqueString + "." + fileType;
        }

        /*
         * 上传文件
         * */
        ossClient.putObject(bucketName, fileName, file.getInputStream());
        String url = "https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + fileName;

        ossClient.shutdown();
        return new Response(1001, url);
    }
}
